<template>
    <div class="el-Map" style="height:500px;width: 100%;position: relative;">
      <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult" style="position: absolute;top: 20px;right: 0;"></el-amap-search-box>
      <el-amap vid="amapDemo" :center="mapCenter" :zoom="zoom" class="amap-demo" :events="events">
        <el-amap-marker :position="marker.position" :events="marker.events" :visible="marker.visible" :draggable="marker.draggable"></el-amap-marker>
      </el-amap>
    </div>
</template>

<script>
  export default {
    props: {
      location: {
        type: Object,
        required: true
      }
    },
    data () {
      return {
        marker: {
          position: [116.397477,39.908692], // 默认天安门坐标
          visible: false,
          draggable: false
        },
        searchOption: {
          city: '全国',
          citylimit: true
        },
        mapCenter: [116.397477, 39.908692], // 默认天安门坐标
        zoom: 14,
        events: {
          click: (el) => {
            this.$emit('locationReport', {
              lng: el.lnglat.lng,
              lat: el.lnglat.lat
            })
            this.marker.visible = true
            this.mapCenter = this.marker.position = [el.lnglat.lng, el.lnglat.lat]
          }
        }
      }
    },
    methods: {
      onSearchResult (el) { // 位置搜索
        let self = this
        if (el.length > 0) {
          this.marker.visible = true
          self.zoom = 18
          self.mapCenter = self.marker.position = [el[0].lng, el[0].lat]
          this.$emit('locationReport', {
            lng: el[0].lng,
            lat: el[0].lat
          })
        }
      }
    },
    watch: {
      location () {
        if (this.location.lat && this.location.lng) {
          this.zoom = 18
          this.mapCenter = this.marker.position = [this.location.lng, this.location.lat]
          this.marker.visible = true
        }
      }
    }
  }
</script>

<style scoped>
  .amap-page-container {
    height: 500px;
  }
</style>
